Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 | 60x 15x 15x 15x 14x 14x 13x 12x 12x 11x 11x 25x 11x 11x 11x 11x 11x 11x 3x 3x 3x 2x 2x 2x 2x 2x 2x 4x 11x 60x 5x 5x 4x 4x 4x 2x 2x 1x 1x 1x 1x 2x 1x 1x 1x 6x 6x 5x 5x 5x 1x 4x 1x 3x 3x 1x 2x 18x 18x 17x 17x 17x 17x 1x 16x 16x 1x 15x 15x 1x 14x 14x 14x 13x 13x 1x 12x 1x 11x 12x 12x 12x 11x 11x 1x 10x 1x 9x 10x 10x 10x 8x 8x 1x 7x 9x 9x 3x 6x 6x 6x 1x 5x 5x 4x 4x 4x 4x 4x 4x 1x 3x 3x 3x 3x 2x 1x 1x 7x 7x 6x 6x 6x 6x 1x 5x 5x 1x 4x 4x 1x 3x 7x 1x 4x 2x 2x 1x 4x 4x 3x 3x 3x 1x 2x 1x | import { error, fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { SetFeeling, type SetPrescription } from '@strengthsys/shared';
// ---------------------------------------------------------------------------
// Route-local view types for prescribed exercises and set logs surfaced to
// the template. Not exported from shared — these shapes are specific to the
// workout detail view.
// ---------------------------------------------------------------------------
export interface PrescribedExerciseView {
id: string;
order: number;
sets: SetPrescription[];
notes: string | null;
exercise_name: string;
}
/**
* Shape returned by the load function for set_logs.
* Used by SetsTable to know which sets are logged AND to pre-fill the
* (editable) inputs for an already-logged set — athletes can correct a set
* after the fact, so the logged actuals must round-trip to the form.
* Also used by the read-only completed view to display actuals and skipped sets.
*/
export interface SetLogView {
id: string;
prescribed_exercise_id: string;
set_number: number;
actual_weight_kg: number | null;
actual_reps: number | null;
feeling: SetFeeling | null;
skipped: boolean;
}
// ---------------------------------------------------------------------------
// Load function
//
// Authorization: request-scoped `locals.supabase` carries the user JWT so RLS
// gates all queries. A workout owned by another athlete returns zero rows from
// `maybeSingle()` (data: null, error: null) → we throw 404, not 500.
//
// Backup filter: `.eq('is_backup', false)` applied at the DB query level.
// Backup rows never reach the client wire format.
// ---------------------------------------------------------------------------
export const load: PageServerLoad = async ({
params,
parent,
locals: { supabase, safeGetSession },
}) => {
// `parent()` inherits the root layout's session. The root layout handles
// unauthenticated → /login. No onboarding redirect lives here — that is
// dashboard-specific (dashboard/+page.server.ts).
await parent();
// Defensive auth check — hooks.server.ts already gates, but belt-and-suspenders.
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const { data: workout, error: wErr } = await supabase
.from('workouts')
.select(
`
id, scheduled_date, session_type, time_cap_minutes, is_deload, status,
location:training_locations ( id, name )
`,
)
.eq('id', params.id)
.maybeSingle();
if (wErr) error(500, 'Failed to load workout');
// RLS null → 404 (cross-athlete or non-existent). No data leak; no crash.
if (!workout) error(404, 'Workout not found');
// Prescribed exercises are only surfaced for non-scheduled workouts.
// The `scheduled` state means the AI has not yet finalised prescriptions.
let exercises: PrescribedExerciseView[] = [];
if (workout.status !== 'scheduled') {
const { data: rows, error: pErr } = await supabase
.from('prescribed_exercises')
.select(
`
id, "order", sets, notes,
exercise:exercises ( name )
`,
)
.eq('workout_id', workout.id)
.eq('is_backup', false)
.order('"order"', { ascending: true });
if (pErr) error(500, 'Failed to load prescribed exercises');
exercises = (rows ?? []).map((row) => ({
id: row.id,
order: row.order,
sets: (row.sets as unknown) as SetPrescription[],
notes: row.notes,
exercise_name: row.exercise?.name ?? '(exercise missing)',
}));
}
// Format session_type for display once, server-side (B1 — single source of truth).
// Capitalizes the first character so templates never need JS or CSS transforms.
const session_type_display =
workout.session_type.charAt(0).toUpperCase() + workout.session_type.slice(1);
// Fetch workout_log_id and set_logs for in_progress or completed workouts.
// The workout_log row is created by ?/start; for ready/scheduled/skipped/rescheduled
// it does not exist. We handle missing rows defensively (workout_log_id: null).
//
// Trust: ?/start guarantees a workout_logs row exists for in_progress/completed
// workouts (via UNIQUE(workout_id)). Even so, we use maybeSingle() for safety.
//
// Phase A (#422): also return overall_feeling + was_scaled from workout_logs,
// and full actuals (actual_weight_kg, actual_reps, feeling, skipped) from set_logs
// so the read-only completed branch in SetsTable can display them.
let workout_log_id: string | null = null;
let workout_log_feeling: string | null = null;
let workout_log_was_scaled = false;
let set_logs: SetLogView[] = [];
if (workout.status === 'in_progress' || workout.status === 'completed') {
const { data: logRow, error: logErr } = await supabase
.from('workout_logs')
.select('id, overall_feeling, was_scaled')
.eq('workout_id', workout.id)
.maybeSingle();
Iif (logErr) error(500, 'Failed to load workout log');
if (logRow) {
const log = logRow as { id: string; overall_feeling?: string | null; was_scaled?: boolean };
workout_log_id = log.id;
workout_log_feeling = log.overall_feeling ?? null;
workout_log_was_scaled = log.was_scaled ?? false;
const { data: setRows, error: setsErr } = await supabase
.from('set_logs')
.select('id, prescribed_exercise_id, set_number, actual_weight_kg, actual_reps, feeling, skipped')
.eq('workout_log_id', logRow.id);
Iif (setsErr) error(500, 'Failed to load set logs');
set_logs = (setRows ?? []).map((r) => ({
id: r.id,
prescribed_exercise_id: r.prescribed_exercise_id,
set_number: r.set_number,
actual_weight_kg: r.actual_weight_kg,
actual_reps: r.actual_reps,
feeling: r.feeling,
skipped: r.skipped ?? false,
}));
}
}
return { workout, exercises, session_type_display, workout_log_id, workout_log_feeling, workout_log_was_scaled, set_logs };
};
// ---------------------------------------------------------------------------
// Form actions — Start, Complete, Skip
//
// All writes use the request-scoped `locals.supabase` so RLS gates every
// mutation by `auth.uid()`. The state-machine trigger
// (`check_workout_status_transition`) enforces allowed transitions on the
// DB side. Each action validates auth, performs the write(s), and returns
// the appropriate result per architect-plan §1.1 + calls A1–A6.
// ---------------------------------------------------------------------------
export const actions: Actions = {
// -------------------------------------------------------------------------
// start: ready → in_progress
//
// Two sequential writes:
// 1. UPDATE workouts SET status='in_progress' WHERE id=:id
// 2. INSERT INTO workout_logs (workout_id, athlete_id, started_at, was_scaled)
//
// Idempotent path (A3): if UPDATE fails with the transition trigger, re-read
// the workout row. If it's already in_progress for this athlete, the intent
// is satisfied — no error surfaced to the athlete. The INSERT is skipped if
// the UNIQUE on workout_logs.workout_id is the constraint (23505).
// -------------------------------------------------------------------------
start: async ({ params, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
// 1. Attempt the status transition.
// `.select('id').maybeSingle()` chained on the UPDATE forces the result to
// include the affected row. When RLS silently filters the UPDATE to 0 rows
// (cross-athlete attack — see Security Reviewer B1), PostgREST returns
// `data: null, error: null` rather than raising. The null-data branch below
// catches that path before we attempt the INSERT, preventing log-row
// poisoning of another athlete's workout.
const { data: updated, error: updateErr } = await supabase
.from('workouts')
.update({ status: 'in_progress' })
.eq('id', workoutId)
.select('id')
.maybeSingle();
if (updateErr) {
// Re-read to check the idempotent path (A3): if the workout is already
// in_progress for this athlete, treat as success.
const { data: existing } = await supabase
.from('workouts')
.select('status, athlete_id')
.eq('id', workoutId)
.maybeSingle();
if (existing?.status === 'in_progress' && existing.athlete_id === user.id) {
// Already in progress — ensure the log row exists (may have been created
// by the first request). If INSERT fails with a UNIQUE violation (23505),
// treat as idempotent success.
const { error: logErr } = await supabase
.from('workout_logs')
.insert({ workout_id: workoutId, athlete_id: user.id, was_scaled: false });
Iif (logErr && logErr.code !== '23505') {
return fail(500, { error: 'Could not create workout log — please try again.' });
}
// Idempotent success; SvelteKit re-runs load.
return;
}
return fail(409, { error: 'Could not start workout — please refresh and try again.' });
}
if (!updated) {
// RLS silently filtered the UPDATE — workout doesn't exist for this
// athlete (cross-athlete or already-deleted). Do NOT attempt the INSERT
// (it would poison another athlete's workout_logs.workout_id slot).
return fail(409, { error: 'Could not start workout — please refresh and try again.' });
}
// 2. INSERT the workout_log row.
const { error: logErr } = await supabase
.from('workout_logs')
.insert({ workout_id: workoutId, athlete_id: user.id, was_scaled: false });
Iif (logErr) {
if (logErr.code === '23505') {
// UNIQUE violation — log already exists (race); idempotent success.
return;
}
return fail(500, { error: 'Could not create workout log — please try again.' });
}
// SvelteKit re-runs load; page rerenders with in_progress state.
},
// -------------------------------------------------------------------------
// complete: in_progress → completed
//
// Two sequential writes (order matters: workout first, log second):
// 1. UPDATE workouts SET status='completed' WHERE id=:id
// 2. UPDATE workout_logs SET completed_at=now() WHERE workout_id=:id AND athlete_id=:uid
//
// After success: redirect(303, '/dashboard') per AC7 / A5.
// The on_workout_completed_request_next trigger fires on the first UPDATE
// when NEW.status='completed' AND OLD.status='in_progress'. We do not
// assert the cascade from this action — see architect-plan A4.
// -------------------------------------------------------------------------
complete: async ({ params, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
// `.select('id').maybeSingle()` catches RLS silent-no-op (cross-athlete) —
// see Security Reviewer B1/N1.
const { data: updated, error: updateErr } = await supabase
.from('workouts')
.update({ status: 'completed' })
.eq('id', workoutId)
.select('id')
.maybeSingle();
if (updateErr) {
return fail(500, { error: 'Could not complete workout — please try again.' });
}
if (!updated) {
return fail(409, { error: 'Could not complete workout — please refresh and try again.' });
}
const { error: logErr } = await supabase
.from('workout_logs')
.update({ completed_at: new Date().toISOString() })
.eq('workout_id', workoutId)
.eq('athlete_id', user.id);
if (logErr) {
return fail(500, { error: 'Could not update workout log — please try again.' });
}
// Return the athlete to the dashboard — finishing a workout must never get
// in the way of leaving the gym (CLAUDE.md: "The system must never get in
// the way of training"). The AFTER-UPDATE trigger has already created the
// post-workout Review (status pending) in the same transaction (#77, spec
// TriggerPostWorkoutReview); it is *offered*, not forced, via the dashboard
// pending-review surface, which shows it once its AI-generated prompts are
// ready (see dashboard/+page.server.ts). We deliberately do NOT redirect
// into /review/[id] here — the spec's 2h-delayed review notification
// (post_workout_review_delay, deferred to #569) confirms the review is
// meant to be picked up later, at the athlete's convenience.
redirect(303, '/dashboard');
},
// -------------------------------------------------------------------------
// logSet: upsert a SetLog row for a prescribed set within an in_progress workout.
//
// Inputs (form data):
// prescribed_exercise_id: uuid (required)
// set_number: string → integer > 0 (required)
// weight_kg: string → null or non-negative float (optional)
// actual_reps: string → null or non-negative integer (optional)
// feeling: one of SetFeeling literals (optional — null when omitted)
//
// Flow:
// 1. Auth guard.
// 2. Validate inputs; first failure returns fail(400).
// 3. Joined lookup: workout_logs + workouts gating on workout.status='in_progress'.
// Satisfies spec/logging.allium:111-112 requires: clauses (defence-in-depth
// with RLS which gates by athlete_id = auth.uid()).
// 4. UPSERT into set_logs (one row per set — re-logging edits in place).
// 5. Return; SvelteKit re-runs load.
// -------------------------------------------------------------------------
logSet: async ({ params, request, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
const formData = await request.formData();
// ── Input validation ──────────────────────────────────────────────────
const prescribedExerciseId = formData.get('prescribed_exercise_id');
if (!prescribedExerciseId || typeof prescribedExerciseId !== 'string' || !prescribedExerciseId.trim()) {
return fail(400, { error: 'prescribed_exercise_id is required.' });
}
const setNumberRaw = formData.get('set_number');
if (!setNumberRaw || typeof setNumberRaw !== 'string') {
return fail(400, { error: 'set_number is required.' });
}
const setNumber = parseInt(setNumberRaw, 10);
if (isNaN(setNumber) || setNumber <= 0) {
return fail(400, { error: 'set_number must be a positive integer.' });
}
const weightRaw = formData.get('weight_kg');
let weightKg: number | null = null;
if (weightRaw !== null && typeof weightRaw === 'string' && weightRaw.trim() !== '') {
const parsed = Number(weightRaw);
if (isNaN(parsed)) {
return fail(400, { error: 'weight_kg must be a number.' });
}
if (parsed < 0) {
return fail(400, { error: 'weight_kg must not be negative.' });
}
weightKg = parsed;
}
const repsRaw = formData.get('actual_reps');
let actualReps: number | null = null;
if (repsRaw !== null && typeof repsRaw === 'string' && repsRaw.trim() !== '') {
const parsed = parseInt(repsRaw, 10);
if (isNaN(parsed)) {
return fail(400, { error: 'actual_reps must be an integer.' });
}
if (parsed < 0) {
return fail(400, { error: 'actual_reps must not be negative.' });
}
actualReps = parsed;
}
// feeling is optional: an athlete may log a set without rating it.
// Absent or empty → null. A present value must be a valid SetFeeling.
const feelingRaw = formData.get('feeling');
let feeling: (typeof SetFeeling)[keyof typeof SetFeeling] | null = null;
if (feelingRaw !== null && typeof feelingRaw === 'string' && feelingRaw.trim() !== '') {
const validFeelings = Object.values(SetFeeling) as string[];
if (!validFeelings.includes(feelingRaw)) {
return fail(400, { error: `feeling must be one of: ${validFeelings.join(', ')}.` });
}
feeling = feelingRaw as (typeof SetFeeling)[keyof typeof SetFeeling];
}
// ── Joined lookup: gates on workout.status = 'in_progress' ───────────
// Satisfies spec/logging.allium:111 requires: workout_log.workout.status = in_progress.
// RLS gates workout_logs by athlete_id = auth.uid() (satisfies :112 requires: workout_log.athlete = athlete).
const { data: log, error: lookupErr } = await supabase
.from('workout_logs')
.select('id, workout:workouts!inner(status)')
.eq('workout_id', workoutId)
.single();
if (lookupErr || !log || (log.workout as { status: string }).status !== 'in_progress') {
return fail(409, { error: 'Could not log set — please refresh and try again.' });
}
const workoutLogId: string = log.id;
// ── Upsert the set_log row ─────────────────────────────────────────────
// onConflict on the natural set key (workout_log, prescribed_exercise,
// set_number) means re-logging the same set EDITS it in place rather than
// appending a duplicate — athletes can correct a logged set ("fat finger").
const { error: upsertErr } = await supabase.from('set_logs').upsert(
{
workout_log_id: workoutLogId,
prescribed_exercise_id: prescribedExerciseId,
set_number: setNumber,
actual_weight_kg: weightKg,
actual_reps: actualReps,
feeling,
skipped: false,
},
{ onConflict: 'workout_log_id,prescribed_exercise_id,set_number' },
);
if (upsertErr) {
return fail(500, { error: 'Could not log set — please try again.' });
}
// SvelteKit re-runs load; page rerenders with the set marked logged.
},
// -------------------------------------------------------------------------
// unlogSet: delete the SetLog row for a prescribed set ("un-tick" a set the
// athlete logged by mistake). Idempotent — deleting a row that isn't there
// is a no-op success.
//
// Inputs (form data):
// prescribed_exercise_id: uuid (required)
// set_number: string → integer > 0 (required)
//
// Gated identically to logSet: workout must be in_progress and owned by the
// caller (joined lookup + RLS via the set_logs_delete policy).
// -------------------------------------------------------------------------
unlogSet: async ({ params, request, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
const formData = await request.formData();
const prescribedExerciseId = formData.get('prescribed_exercise_id');
Iif (!prescribedExerciseId || typeof prescribedExerciseId !== 'string' || !prescribedExerciseId.trim()) {
return fail(400, { error: 'prescribed_exercise_id is required.' });
}
const setNumberRaw = formData.get('set_number');
if (!setNumberRaw || typeof setNumberRaw !== 'string') {
return fail(400, { error: 'set_number is required.' });
}
const setNumber = parseInt(setNumberRaw, 10);
Iif (isNaN(setNumber) || setNumber <= 0) {
return fail(400, { error: 'set_number must be a positive integer.' });
}
// Gate on workout.status = 'in_progress' (spec/logging.allium:111).
const { data: log, error: lookupErr } = await supabase
.from('workout_logs')
.select('id, workout:workouts!inner(status)')
.eq('workout_id', workoutId)
.single();
if (lookupErr || !log || (log.workout as { status: string }).status !== 'in_progress') {
return fail(409, { error: 'Could not update set — please refresh and try again.' });
}
const { error: deleteErr } = await supabase
.from('set_logs')
.delete()
.eq('workout_log_id', log.id)
.eq('prescribed_exercise_id', prescribedExerciseId)
.eq('set_number', setNumber);
Iif (deleteErr) {
return fail(500, { error: 'Could not update set — please try again.' });
}
// SvelteKit re-runs load; the set returns to its unlogged (editable) state.
},
// -------------------------------------------------------------------------
// completeAllSets: mark every prescribed set of one exercise as completed at
// the prescribed weight/reps in a single tap ("Complete all as prescribed").
//
// Inputs (form data):
// prescribed_exercise_id: uuid (required)
//
// Reads the exercise's prescription (sets jsonb) and upserts one SetLog per
// set with actual_weight_kg = target_weight_kg, actual_reps = target_reps,
// feeling = null. Upsert means it composes with any already-logged sets and
// is safe to re-run.
// -------------------------------------------------------------------------
completeAllSets: async ({ params, request, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
const formData = await request.formData();
const prescribedExerciseId = formData.get('prescribed_exercise_id');
if (!prescribedExerciseId || typeof prescribedExerciseId !== 'string' || !prescribedExerciseId.trim()) {
return fail(400, { error: 'prescribed_exercise_id is required.' });
}
// Gate on workout.status = 'in_progress' (spec/logging.allium:111).
const { data: log, error: lookupErr } = await supabase
.from('workout_logs')
.select('id, workout:workouts!inner(status)')
.eq('workout_id', workoutId)
.single();
if (lookupErr || !log || (log.workout as { status: string }).status !== 'in_progress') {
return fail(409, { error: 'Could not complete sets — please refresh and try again.' });
}
// Read the prescription so we know how many sets and their targets.
// RLS gates prescribed_exercises by the owning athlete; a foreign id
// yields null → 409.
const { data: pe, error: peErr } = await supabase
.from('prescribed_exercises')
.select('sets')
.eq('id', prescribedExerciseId)
.maybeSingle();
if (peErr || !pe) {
return fail(409, { error: 'Could not complete sets — please refresh and try again.' });
}
const sets = (pe.sets as unknown as SetPrescription[]) ?? [];
if (sets.length === 0) {
return fail(400, { error: 'This exercise has no prescribed sets.' });
}
const rows = sets.map((s, i) => ({
workout_log_id: log.id,
prescribed_exercise_id: prescribedExerciseId,
set_number: i + 1,
actual_weight_kg: s.target_weight_kg,
actual_reps: s.target_reps,
feeling: null,
skipped: false,
}));
const { error: upsertErr } = await supabase
.from('set_logs')
.upsert(rows, { onConflict: 'workout_log_id,prescribed_exercise_id,set_number' });
if (upsertErr) {
return fail(500, { error: 'Could not complete sets — please try again.' });
}
// SvelteKit re-runs load; every set for the exercise renders as logged.
},
// -------------------------------------------------------------------------
// skip: {ready, in_progress} → skipped
//
// Single write: UPDATE workouts SET status='skipped' WHERE id=:id
// The state-machine trigger admits both ready→skipped and in_progress→skipped.
// No workout_logs mutation regardless of starting state (A6 negative invariant:
// workout_logs.completed_at remains NULL for in_progress→skipped, confirming
// the cascade WHEN predicate excludes this transition).
//
// After success: SvelteKit re-runs load; page rerenders with skipped terminal state.
// -------------------------------------------------------------------------
skip: async ({ params, locals: { supabase, safeGetSession } }) => {
const { user } = await safeGetSession();
if (!user) redirect(303, '/login');
const workoutId = params.id;
// `.select('id').maybeSingle()` catches RLS silent-no-op (cross-athlete) —
// see Security Reviewer B1/N1.
const { data: updated, error: updateErr } = await supabase
.from('workouts')
.update({ status: 'skipped' })
.eq('id', workoutId)
.select('id')
.maybeSingle();
if (updateErr) {
return fail(500, { error: 'Could not skip workout — please try again.' });
}
if (!updated) {
return fail(409, { error: 'Could not skip workout — please refresh and try again.' });
}
// SvelteKit re-runs load; page renders the skipped terminal state.
},
};
|